// Copyright (C) 2011 YANG Hao (yangh2007@gmail.com). All rights reserved.
//
// This file is part of the (cute)octopus project.
//
// This file may be distributed and/or modified under the terms of the
// GNU General Public License version 2 as published by the Free Software
// Foundation.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Author(s): YANG Hao


#include "owindow.h"

#include <QGraphicsView>
#include "odoc.h"

OWindow::OWindow(ODoc* doc, QWidget *parent /* = 0 */)
: QMdiSubWindow(parent), m_doc(doc){
	//w->installEventFilter(this); 
	if(!doc->rel_winds.contains(this)){
		doc->rel_winds.append(this);
		m_doc = doc;
	}
	setWindowTitle(doc->filePath());
	setWindowIcon(doc->icon());
	setAttribute(Qt::WA_DeleteOnClose, true);
}

OWindow::~OWindow(){}

void OWindow::updateFilePath() {setWindowTitle(m_doc->filePath());}

bool OWindow::eventFilter(QObject *obj, QEvent *ev)
{
	if(ev->type() < QEvent::User)
		return QMdiSubWindow::eventFilter(obj, ev);
	QWidget* widget = qobject_cast<QWidget*>(obj);
	if(ev->type() == OStd::Event_WidgetUpdate){
		QGraphicsView* v = dynamic_cast<QGraphicsView*>(widget);
		v ? v->invalidateScene() : widget->repaint();
		if(m_doc){
			m_doc->lock();
			m_doc->m_waitingForWidgetUpdate = false;
			m_doc->unlock();
		}
		return false;
	}else
		return true;
}

void OWindow::closeEvent(QCloseEvent *closeEvent)
{
	m_doc->rel_winds.removeOne(this);
	if(!m_doc->hasWindows())
		oApp()->closeDoc(m_doc->filePath());
}